<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <!-- 总添加 -->
      <el-tree
        :data="compony"
        :props="defaultProps"
        style="margin-bottom: 15px"
      >
        <template v-slot="{ data }">
          <TreeNode :node="data" :boo="false" @addDept="addDept" />
        </template>
      </el-tree>

      <!-- 子部门 -->
      <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
        <template v-slot="{ data }">
          <TreeNode
            :node="data"
            @delDept="delDept"
            @addDept="addDept"
            @editDept="editDept"
          />
        </template>
      </el-tree>

      <!-- 部门操作弹层 -->
      <EditPup
        ref="edit"
        :operate-pup-show="operatePupShow"
        :node="node"
        :depts="list"
        @close="operatePupShow = false"
        @addDeptOk="addDeptOk"
      />
    </div>
  </div>
</template>

<script>
import EditPup from './components/edit-pup.vue'
import { dataToTree } from '@/utils/validate'
import TreeNode from './components/tree-node.vue'
import { mapGetters } from 'vuex'
import { getDepartList, delDepart } from '@/api/depart'
export default {
  name: 'DepartMent',
  components: {
    TreeNode,
    EditPup
  },
  data() {
    return {
      list: [],
      compony: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      operatePupShow: false,
      node: {} // 点击的节点
    }
  },
  computed: {
    ...mapGetters(['name']),
    depts() {
      return dataToTree(this.list, '')
    }
  },
  created() {
    this.getDepartList()
  },
  methods: {
    // 获取部门列表
    async getDepartList() {
      const res = await getDepartList()
      console.log(res)
      this.compony = [{ name: res.companyName, manager: '负责人', id: '' }]
      this.list = res.depts.slice(1)
    },
    // 添加部门按钮被点击
    addDept($event) {
      this.node = $event
      this.operatePupShow = true
    },
    // 添加部门按钮被点击
    editDept($event) {
      this.node = $event
      this.operatePupShow = true
      this.$nextTick(() => {
        this.$refs.edit.getDepartDetail()
      })
    },
    // 删除部门按钮被点击
    async delDept(node) {
      await delDepart(node.id)
      this.$message('删除成功')
      this.getDepartList()
    },
    // 添加部门确定
    addDeptOk() {
      this.operatePupShow = false
      this.getDepartList()
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 16px;
    line-height: 46px;
  }
}
</style>
